<template>
  <div>
    <div class="code-chinese">登录国家税务局账号</div>
    <el-card class="login-form-layout">
      <el-form
        v-if="!phoneNumberShow"
        autoComplete="on"
        :model="loginForm"
        :rules="loginRules"
        ref="loginForm"
        label-position="left"
        style="padding: 15px"
      >
        <div class="login-title">企业业务</div>
        <el-form-item prop="provinceName" class="address-main">
          <el-select
            style="width: 100%"
            v-model="loginForm.provinceName"
            class="custom-select"
            filterable
            placeholder="请选择企业所在省份"
            :prefix-icon="customIconClass"
          >
            <div slot="prefix" style="margin-top: 3px">
              <img
                style="width: 16px; height: 18px; line-height: 18px"
                src="../../../assets/icon/prvice.png"
              />
            </div>
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="creditCodeOrTaxPayerId">
          <el-input
            name="creditCodeOrTaxPayerId"
            type="text"
            v-model="loginForm.creditCodeOrTaxPayerId"
            autoComplete="on"
            placeholder="统一社会信用代码/纳税人识别号"
          >
            <div slot="prefix" style="margin-top: 3px">
              <img
                style="width: 16px; height: 18px; line-height: 18px"
                src="../../../assets/icon/code.png"
              />
            </div>
          </el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input
            name="phoneNumber"
            type="text"
            v-model="loginForm.phoneNumber"
            maxlength="11"
            autoComplete="on"
            placeholder="居民身份证号码/手机号/用户名"
          >
            <div slot="prefix" style="margin-top: 3px">
              <img
                style="width: 15px; height: 18px; line-height: 18px"
                src="../../../assets/icon/mobile.png"
              />
            </div>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :type="pwdType"
            @keyup.enter.native="handleLogin"
            v-model="loginForm.password"
            autoComplete="on"
            placeholder="请输入密码"
          >
            <div slot="prefix" style="margin-top: 3px">
              <img
                style="width: 15px; height: 18px; line-height: 18px"
                src="../../../assets/icon/lock.png"
              />
            </div>
            <span slot="suffix" @click="showPwd">
              <svg-icon icon-class="eye" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 60px; text-align: center">
          <el-button
            v-debounce
            style="width: 100%"
            type="primary"
            :loading="loading"
            @click.native.prevent="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div v-if="phoneNumberShow">
        <div class="code-login" @click="goback">
          <div><i class="el-icon-arrow-left"></i>返回</div>
          <div>企业登陆</div>
        </div>
        <el-form :model="codeForm" style="padding: 15px">
          <el-form-item class="mt30">
            <el-input
              name="username"
              disabled
              type="text"
              v-model="codeForm.phoneNumber"
              autoComplete="on"
            >
              <div slot="prefix" style="margin-top: 3px">
                <img
                  style="width: 15px; height: 18px; line-height: 18px"
                  src="../../../assets/icon/mobile.png"
                />
              </div>
            </el-input>
          </el-form-item>
          <el-form-item class="mt30">
            <div style="display: flex">
              <el-input
                maxlength="6"
                name="username"
                :disabled="codeDisabled"
                v-model="codeForm.code"
                autoComplete="on"
                placeholder="请输入短信验证码"
              >
                <div slot="prefix" style="margin-top: 4px">
                  <img
                    style="
                    width: 16px;
                    height: 18px;
                    line-height: 18px;
                    margin-left: 2px;
                  "
                    src="../../../assets/icon/code01.png"
                  />
                </div>
              </el-input>
              <el-button
                class="btnSty"
                :disabled="btndisabled"
                type="primary"
                @click="sendCode"
                >{{ btnName }}</el-button
              >
            </div>
          </el-form-item>
          <el-form-item class="mt30">
            <el-button
              v-debounce
              style="width: 100%; margin: 50px 0"
              @click="loginHandle()"
              type="primary"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { isvalidUsername } from "@/utils/validate";
import { setSupport, getSupport, setCookie, getCookie } from "@/utils/support";
import {
  login,
  sendCode,
  smsMsLogin,
  getProvinceList,
  getCompanyInfo,
  noCodeL
} from "@/api/tax";
import store from "../../../store";
// import {} from '../../../utils/'

export default {
  name: "login",
  data() {
    //这个方法要写在用到这个方法的地方的前面
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3-9][0-9]\d{8}$/;
        // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
        if (reg.test(value)) {
          callback();
        } else {
          // 具体错误信息没有提示
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };

    return {
      customIconClass: "el-icon-document",
      provinceList: [],

      //第一次登录的表单
      loginForm: {
        creditCodeOrTaxPayerId: "",
        password: "",
        phoneNumber: "",
        provinceName: ""
      },
      //验证码表单
      codeForm: {
        phoneNumber: "",
        code: ""
      },
      phoneNumberShow: false,
      //登录表单验证规则
      loginRules: {
        creditCodeOrTaxPayerId: [
          {
            required: true,
            trigger: "blur",
            message: "请输入统一社会信用代码/纳税人识别号"
          }
        ],
        phoneNumber: [
          { min: 11, message: "手机号不足11位", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" }
        ],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
        provinceName: [
          { required: true, message: "请选择企业所在省份", trigger: "change" }
        ]
      },
      loading: false,
      pwdType: "password",
      time: null, // 倒计时默认60秒
      btndisabled: true, //按钮是否禁用
      enterpriseId: "", //企业id
      uuid: "",
      eid: "",
      codeDisabled: true,
      timecount: null,
      needCityCodeList: ["zhejiang", "hubei", "guangdong"]
    };
  },
  activated() {
    if (this.$store.getters.enterpriseId) {
      this.eid = this.$store.getters.enterpriseId;

      getCompanyInfo({
        enterpriseId: this.eid
      }).then(res => {
        this.loginForm = {
          creditCodeOrTaxPayerId: res.data.creditCodeOrTaxPayerId,
          password: res.data.password,
          phoneNumber: res.data.phoneNumber,
          provinceName: res.data.provinceName
        };
      });
    } else {
      this.restLoginForm();
    }
  },
  deactivated() {
    this.$store.commit("REMOVE_ENTERPRISEID");
    clearInterval(this.timecount);
  },
  computed: {
    //计算处理按钮名字
    btnName() {
      if (this.time == 0) {
        this.btndisabled = false;
        return "重新发送";
      } else if (this.time > 0 && this.time < 60) {
        this.btndisabled = true;
        return `(${this.time}后重新发送)`;
      } else if (this.time == 60) {
        this.btndisabled = false;
        return `发送验证码`;
      }
    }
  },
  created() {
    this.$nextTick(() => {
      //获取省份列表
      this.getProvinceList();
    });
  },
  methods: {
    restLoginForm() {
      this.loginForm = {
        creditCodeOrTaxPayerId: "",
        password: "",
        phoneNumber: "",
        provinceName: ""
      };
      this.codeForm = {
        phoneNumber: "15091716704",
        code: ""
      };
      this.phoneNumberShow = false;
      this.btndisabled = false;
      this.$set(this, "time", 60);
      // this.time = 60;
    },
    //获取省份列表
    getProvinceList() {
      getProvinceList().then(res => {
        const provinceList = res.data.map(v => {
          return {
            id: v.id,
            name: v.name,
            value: v.pinyin
          };
        });
        this.provinceList = provinceList;
      });
    },
    //登录
    /**
     * 处理登录逻辑。
     * 无参数。
     * 无明确返回值，但会触发登录成功后的相关操作。
     */
    loginHandle() {
      let codeReg = /^\d{6}$/;
      if (!codeReg.test(this.codeForm.code))
        return this.$message.error("请输入6位数字的验证码");
      // 准备登录参数
      let params = {
        code: this.codeForm.code, // 验证码
        creditCodeOrTaxPayerId: this.loginForm.creditCodeOrTaxPayerId, // 信用代码或纳税人ID
        enterpriseId: this.enterpriseId + "", // 企业ID
        password: this.loginForm.password, // 密码
        phoneNumber: this.loginForm.phoneNumber, // 电话号码
        provinceName: this.loginForm.provinceName, // 省份名称
        uuid: this.uuid // 唯一标识符
      };
      // 发起登录请求
      smsMsLogin(params).then(res => {
        this.$emit("initMenu"); // 触发初始化菜单事件
        // 创建登录成功后的用户信息对象
        let obj = {
          type: 1, // 用户类型
          name: "", // 用户名
          enterpriseId: this.enterpriseId + "", // 企业ID
          queryStatus: res.data.queryStatus, // 查询状态
          phone: this.loginForm.phoneNumber, // 电话号码
          id: res.data.id + "" //res.data.id 任务ID
        };
        this.$message.success("登录成功"); // 显示登录成功消息
        this.$emit("loginIn", obj); // 触发登录成功事件，传递用户信息
      });
    },

    goback() {
      clearInterval(this.timecount);
      this.phoneNumberShow = false;
    },
    timer() {
      clearInterval(this.timecount);
      this.timecount = null;
      this.timecount = setInterval(() => {
        this.time--;
        if (this.time < 1) {
          clearInterval(this.timecount);
          this.timecount = null;
        }
      }, 1000);
    },
    //发送验证码
    sendCode() {
      if (this.codeForm.phoneNumber == "") {
        this.$message.error("手机号不能为空");
        return false;
      } else if (
        !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
          this.codeForm.phoneNumber
        )
      ) {
        this.$message.error("手机号不正确");
        return false;
      } else if (this.codeForm.phoneNumber.length != 11) {
        this.$message.error("手机号不正确");
        return false;
      } else {
        //向后台发送请求

        sendCode({
          phone: this.codeForm.phoneNumber,
          creditCodeOrTaxPayerId: this.loginForm.creditCodeOrTaxPayerId,
          uuid: this.uuid
        }).then(res => {
          this.$set(this, "time", 59);
          this.timer(); //开始倒计时
          this.codeDisabled = false;
          this.btndisabled = true;
          return this.$message.success(res.message);
        });
      }
    },
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },

    //登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          let params = Object.assign({}, this.loginForm);
          params.provinceId = this.provinceList.find(
            v => v.value == params.provinceName
          ).id;
          if (this.needCityCodeList.includes(params.provinceName)) {
            this.noCodeLogin(params);
          } else {
            login(params).then(res => {
              // todo 判断是否需要验证码or直接拉取数据 用状态码判断
              // this.enterpriseId = res.data.enterpriseId;

              if (res.data.code !== 0) {
                return this.$message.error(res.data.message);
              }
              this.enterpriseId = res.data.enterpriseId;

              this.uuid = res.data.uuid;
              clearInterval(this.timecount);
              this.noOntherLogin2(res.data);
              // 判断是否在需要验证码列表内
            });
          }
        } else {
          // console.log("参数验证不合法！");
          return false;
        }
      });
    },
    //天津 不需要验证码登录
    noCodeLogin(data) {
      let params = {
        provinceName: data.provinceName,
        creditCode: this.loginForm.creditCodeOrTaxPayerId,
        phone: this.loginForm.phoneNumber,
        password: this.loginForm.password,
        provinceId: data.provinceId
      };
      noCodeL(params).then(res => {
        this.$emit("initMenu"); // 触发初始化菜单事件
        // 创建登录成功后的用户信息对象
        let obj = {
          type: 1, // 用户类型
          name: "", // 用户名
          enterpriseId: res.data.enterpriseId, // 企业ID
          queryStatus: res.data.queryStatus, // 查询状态
          phone: this.loginForm.phoneNumber, // 电话号码
          id: res.data.id //res.data.id 任务ID
        };

        console.log(obj, "obj");
        this.$message.success("登录成功"); // 显示登录成功消息
        this.$emit("loginIn", obj); // 触发登录成功事件，传递用户信息
      });
    },
    //非天津 登录
    noOntherLogin2(data) {
      if (data.needSendCaptchaCode == 0) {
        this.$emit("initMenu");
        // type, name, enterpriseId, queryStatus, phone, id
        let obj = {
          type: 1,
          name: "",
          enterpriseId: this.enterpriseId,
          queryStatus: data.queryStatus,
          phone: this.loginForm.phoneNumber,
          id: data.queryTaskId + "" //  res.data.id 任务ID
        };
        this.$message.success("数据已同步");
        this.$emit("loginIn", obj);
      } else {
        // this.time = 60;
        this.$set(this, "time", 60);

        setTimeout(() => {
          this.codeForm.phoneNumber = this.loginForm.phoneNumber;
          this.phoneNumberShow = true;
        }, 500);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.mt30 {
  margin-top: 30px;
}
.code-chinese {
  text-align: center;
  margin: 30px 0;
  color: #000;
  font-weight: bold;
  font-size: 30px;
}

.login-title {
  margin: 10px 0 40px;
  font-weight: bold;
  color: #222;
  font-size: 20px;
  text-align: center;
}
.code-login {
  display: flex;
  align-items: center;
  > div {
    width: 40%;
    &:nth-child(1) {
      color: #999;
    }
    &:nth-child(2) {
      font-size: 20px;
      font-weight: bold;
    }
  }
  // justify-content: space-between;
}

.login-center-layout {
  background: #409eff;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
  .address-main {
    position: relative;
    .addressicon {
      position: absolute;
      left: 0;
      top: 0;
    }
  }
}
.el-input__inner {
  border-radius: 0 !important;
}
.btnSty {
  width: 150px;
  background-color: #409eff !important;
  color: #fff !important;
  border-radius: 0 !important;
}
.el-button.is-disabled,
.el-button.is-disabled:focus,
.el-button.is-disabled:hover {
  background-color: #f5f7fa !important;
  color: red !important;
}
.custom-select .el-input__inner::before {
  content: "\e61d" !important;
  font-family: "element-icons" !important;
  position: absolute !important;
  left: 10px !important;
  top: 50% !important;
  transform: translateY(-50%) !important;
}

.custom-select .el-input__prefix i {
  display: none !important;
}
</style>
